<template>
	<div class="system-role">
        <Modal v-model="showPermissionModal" width="360">
            <p slot="header" style="color:#f60">
                <!-- <Icon type="ios-information-circle"></Icon> -->
                <span>权限详情</span>
            </p>
            <div>
                <p v-for="(item,i) in permissionIds" :key="i">{{item.permissionName}}</p>
            </div>
        </Modal>
		<div class="top">
			<Row :gutter="10" justify="center">
				<Col span="4">
					<Button type="success" icon="md-add" @click="showDrawer=true;">新增</Button>
				</Col>
			</Row>
		</div>
		<Drawer :title="alertTitle" v-model="showDrawer" :width="720" :mask-closable="false">
			<Form :model="editedItem">
				<Row :gutter="32">
					<Col span="12">
						<FormItem label="角色名称" label-position="top">
							<Input v-model="editedItem.rolename" placeholder="请输入角色名称" />
						</FormItem>
					</Col>
					<Col span="12">
						<FormItem label="状态" label-position="top">
							<Input v-model="editedItem.status" placeholder="请输入状态" />
						</FormItem>
					</Col>
				</Row>
				<Row :gutter="32">
					<Col span="24">
						<FormItem label="权限" label-position="top">
							<!-- <Input v-model="editedItem.rolename" placeholder="请输入角色名称" /> -->
							<Select v-model="editedItem.permissionIds" multiple :max-tag-count="10" placeholder="请选择权限">
								<Option v-for="item in permissionList" :value="item.permissionId" :key="item.id">{{ item.resourceName}}</Option>
							</Select>
						</FormItem>
					</Col>
				</Row>
			</Form>
			<div class="demo-drawer-footer">
				<Button style="margin-right: 8px" @click="close">取消</Button>
				<Button type="primary" :loading="editedIndex===-1?createLoading:updateLoading" @click="save">保存</Button>
			</div>
		</Drawer>
		<div>
			<div>
				<Table
					:loading="loading"
					highlight-row
					ref="currentRowTable"
					:columns="tableColumns"
					:data="items"
				>
                    <template slot-scope="{ row }" slot="sex">
                        <span v-if="Number(row.sex)===1">男</span>
                        <span v-else-if="Number(row.sex)===2">女</span>
                        <span v-else>-</span>
                    </template>
					<template slot-scope="{row}" slot="createTime">
						<span>{{row.createTime | YMDHMS}}</span>
					</template>
					<template slot-scope="{row}" slot="updateTime">
						<span>{{row.updateTime | YMDHMS}}</span>
					</template>
					<template slot-scope="{row}" slot="action">
						<Button type="primary" size="small" @click="detail(row)">权限详情</Button>
						<Button  type="primary" size="small" @click="update(row)">修改</Button>
						<Button v-if="row.rolename !== 'ADMIN'" class="ml10" type="primary" ghost size="small" @click="remove(row)">删除</Button>
					</template>
				</Table>
                <Row class="pagination">
                    <Col align="right">
                        <Page :current="page" :total="totalNum" show-total @on-change="pageChange" />
                    </Col>
                </Row>
			</div>
		</div>
	</div>
</template>
<script>
import { roleGet, roleUpdate, roleDelete, roleAdd, rolePageQueryList } from '../../../api/role.js'
import { resourceQueryListByParentId } from '../../../api/resource.js'

export default {
	data() {
		return {
            showDrawer: false,
            showPermissionModal: false,
			loading: false,
            createLoading: false,
            updateLoading: false,
            removeLoading: false,
            editedIndex: -1,
            permissionIds: [],
			editedItem: {
				rolename: '',
				status: '',
				permissionIds: []
			},
			defaultItem: {
				rolename: '',
				status: '',
				permissionIds: []
            },
			items: [],
			page: 1,
			pageSize: 10,
			totalNum: 0,
			permissionList: [],
			tableColumns: [
				{
					title: '角色id',
					key: 'id'
				},
				{
					title: '角色名称',
					key: 'rolename'
				},
				{
					title: '状态',
					key: 'status'
				},
				{
					title: '创建时间',
					slot: 'createTime'
				},
				{
					title: '更新时间',
					slot: 'updateTime'
				},
				{
					title: '操作',
					slot: 'action',
					width: 200
				}
			]
		}
	},
	mounted() {
		this.rolePageQueryList()
		this.resourceQueryListByParentId()
	},
	computed: {
		alertTitle() {
			return this.editedIndex === -1 ? '新增' : '修改'
		}
	},
	methods: {
		resourceQueryListByParentId() {
			resourceQueryListByParentId({ parentId: -1 }).then(res => (this.permissionList = res.code === '0' ? res.data : []))
		},
		pageChange(page) {
            if (this.loading) {
                return;
            }
			this.page = page
			this.rolePageQueryList()
			console.log('page>', page)
		},
		async update(item) {
            const { id } = item;
			this.editedIndex = item._index
			this.editedItem = Object.assign({}, item)
            this.showDrawer = true
            const res = await roleGet({id})
            if (res.code === "0") {
                const { permissions } = res.data;
                permissions.map((item,i) => permissions[i] = item.id)
                this.editedItem = {...this.editedItem,...{permissionIds: permissions}}
            }
		},
		create() {
			this.editedIndex = -1
			this.editedItem = Object.assign({}, this.defaultItem)
			this.showDrawer = true
		},
		remove(item, idx) {
            //done this.close();
            const { rolename ,id} = item;
            this.removeLoading || (this.removeLoading = true)
            this.$Modal.confirm({
                loading: this.removeLoading,
                title: '删除',
                content: `是否删除角色: ${rolename}?`,
                onOk: async () => {
                    const res = await roleDelete({id})
                    this.modal(res,'删除');
                    this.rolePageQueryList();
                    this.$Modal.remove();
                    this.removeLoading = false;
                }
            })
        },
		async save() {
			console.log('this.$Modal-->', this.$Modal)
			if (this.editedIndex > -1) {
				console.log('update...')
                const { id, status, rolename, permissionIds } = this.editedItem
                this.updateLoading || (this.updateLoading = true);
                const res = await roleUpdate({ id, status, rolename, permissionIds })
                this.updateLoading = false
                this.modal(res)
			} else {
				console.log('create...')
                const { status, rolename, permissionIds } = this.editedItem
                this.createLoading || (this.createLoading = true);
                const res = await roleAdd({ status, rolename, permissionIds })
                this.createLoading = false
				this.modal(res)
				//create
			}
			this.rolePageQueryList()
			this.close()
        },
        modal(res,title){
            if (res.code === "0") {
                this.$Modal.success({
                    title: title || this.alertTitle,
                    content: res.data
                })
            } else {
                this.$Modal.warning({
                    title: title || this.alertTitle,
                    content: res.errMsg
                })
            }
        },
		close() {
			this.showDrawer = false
			setTimeout(() => {
				this.editedItem = Object.assign({}, this.defaultItem)
				this.editedIndex = -1
			}, 10)
		},
        detail(row) {
            const{ id } = row;
            this.permissionIds = [{permissionName:'加载中...'}];
            roleGet({id}).then(res => {
                if (res.code === "0") {
                    this.permissionIds = [];
                    this.permissionIds = res.data.permissions;
                }
            })
            this.showPermissionModal = true;
        },
		rolePageQueryList() {
			const { page, pageSize, loading } = this
			if (loading) return
			this.loading = true
			rolePageQueryList({
				page,
				pageSize
			})
				.then(res => {
					this.loading = false
					console.log('res roles->', res)
					if (res.code === '0') {
						const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data
						;(this.items = items), (this.page = currentPage), (this.totalNum = totalNum)
						console.log('this.items->', this.items)
					} else {
                        this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
					    })
                    }
				})
				.catch(err => {
					this.loading = false
				})
		}
	},
	watch: {
		showDrawer(after) {
			after || this.close()
		}
	}
}
</script>
<style scoped>
.system-role {
	background-color: #fff;
}
</style>